let videoPlayer = document.getElementById('videoPlayer');
let audioplayer = document.getElementById('audioplayer');
let divConstraints = document.getElementById('constraints');

var buffer;
var mediaRecorder;

function gotMediaStream(stream) {
    videoPlayer.srcObject = stream;
    // audioplayer.srcObject = stream;
    var videoTrack = stream.getVideoTracks()[0];
    var videoConstraints = videoTrack.getSettings();

    window.stream = stream;
    divConstraints.textContent = JSON.stringify(videoConstraints, null, 2);

    return navigator.mediaDevices.enumerateDevices();
}

function handleError(err) {
    console.log("getUserMedia error:", err);
}

// picture
let snapshot = document.getElementById('snapshot');
let picture = document.getElementById('picture');
picture.width = 320;
picture.height = 240;

//filter
let filterSeletor = document.getElementById('filter');

//录制相关的dom
let btnPlay = document.getElementById('recordPlay');
let btnRecord = document.getElementById('record');
let btnDownLoad = document.getElementById('download');
let RecordPlayer = document.getElementById("RecordPlayer");

function gotDevices(deviceInfos) {
    deviceInfos.forEach(deviceInfo => {
        console.log("Kind: ", deviceInfo.kind);
        console.log("Label: ", deviceInfo.label);
        console.log("Device ID: ", deviceInfo.deviceId);
        console.log("Group ID: ", deviceInfo.groupId);
        console.log("\n");

        let option = document.createElement('option');
        option.text = deviceInfo.label;
        option.value = deviceInfo.deviceId;

        if(deviceInfo.kind === 'videoinput') {
            document.getElementById('videoInput').appendChild(option);
        } else if(deviceInfo.kind === 'audioinput') {
            document.getElementById('audioInput').appendChild(option);
        } else if(deviceInfo.kind === 'audiooutput') {
            document.getElementById('audioOutput').appendChild(option);
        }
    });
}

function start() {
    if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        console.log("getUserMedia() is not supported.");
    } else {
        let constraints = {
            audio: {
                noiseSuppression: true,
                echoCancellation: true
            },
            video: {
                width:320,
                height:240
            }
        }
        // let constraints = {
        //     audio: true,
        //     video: false
        // }
        navigator.mediaDevices.getUserMedia(constraints)
            .then(gotMediaStream)
            .then(gotDevices)
            .catch(handleError);
    }
}

start();
videoPlayer.onchange = start;

// 按钮截屏
snapshot.onclick = function() {
    let context = picture.getContext('2d');
    context.drawImage(videoPlayer, 0, 0, picture.width, picture.height);
}

// 滤镜
filterSeletor.onchange = function() {
    videoPlayer.className = filterSeletor.value;
}

function handleDataAvailable(e) {
    if(e && e.data && e.data.size > 0) {
        buffer.push(e.data);
    }
}

function startRecord() {
    buffer = [];
    var options = {
        mimeType: 'video/webm;codecs=vp8'
    }
    if(!MediaRecorder.isTypeSupported(options.mimeType)) {
        console.error(`${options.mimeType} is not supported!`);
        return;
    }
    try {
        mediaRecorder = new MediaRecorder(window.stream, options);
    } catch (e) {
        console.error('Failed to create MediaRecorder:', e);
        return;
    }

    mediaRecorder.ondataavailable = handleDataAvailable;
    mediaRecorder.start(10);
}

function stopRecord() {
    mediaRecorder.stop();
}

// 录制按钮
btnRecord.onclick = function() {
    if(btnRecord.textContent === 'Start Record') {
        startRecord();
        btnRecord.textContent = 'Stop Record';
        btnPlay.disabled = true;
        btnDownLoad.disabled = true;
    } else {
        stopRecord();
        btnRecord.textContent = 'Start Record';
        btnPlay.disabled = false;
        btnDownLoad.disabled = false;
    }
}

btnPlay.onclick = () => {
    let blob = new Blob(buffer, {type: 'video/webm'});
    RecordPlayer.src = window.URL.createObjectURL(blob);
    RecordPlayer.srcObject = null;
    RecordPlayer.controls = true;
    RecordPlayer.play();
}

btnDownLoad.onclick = () => {
    let blob = new Blob(buffer, {type: 'video/webm'});
    let url = window.URL.createObjectURL(blob);
    let a = document.createElement('a');

    a.href = url;
    a.style.display = 'none';
    a.download = 'aaa.webm';
    a.click();
}